package com.fowo.api.syncLingxingApi.service.syncImpl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.fowo.api.syncLingxingApi.entity.TmpSyncLingxingToWmsOrderList;
import com.fowo.api.syncLingxingApi.service.SyncLxApiBaseService;
import com.fowo.api.syncLingxingApi.service.impl.TmpSyncLingxingToWmsOrderListServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
@Slf4j
@DS("ds24")
public class SyncLxWmsOrderListServiceImpl
        extends SyncLxApiBaseService<TmpSyncLingxingToWmsOrderList, TmpSyncLingxingToWmsOrderList> {
    private static final String LX_API_URL_KEY = "wmsOrderListUrl";
    private static final int MAX_LEN = 50;

    @Resource
    private TmpSyncLingxingToWmsOrderListServiceImpl service;

    public SyncLxWmsOrderListServiceImpl() {
        super(LX_API_URL_KEY, MAX_LEN);
    }

    @Override
    protected JSONObject pullLingxingData(long offset, long length, JSONObject params) {
        Map<String, Object> reqBody = new HashMap<>();
        long page = (int)(offset / length) + 1;
        reqBody.put("page", page);
        reqBody.put("page_size", length);
        if (params != null) {
            if (params.containsKey("sid_arr"))
                reqBody.put("sid_arr", params.getJSONArray("sid_arr").toJavaList(String.class));
            if (params.containsKey("status_arr"))
                reqBody.put("status_arr", params.getJSONArray("status_arr").toJavaList(String.class));
            if (params.containsKey("logistics_status_arr"))
                reqBody.put("logistics_status_arr", params.getJSONArray("logistics_status_arr").toJavaList(String.class));
            if (params.containsKey("time_type"))
                reqBody.put("time_type", params.getString("time_type"));
            if (params.containsKey("start_date"))
                reqBody.put("start_date", params.getString("start_date"));
            if (params.containsKey("end_date"))
                reqBody.put("end_date", params.getString("end_date"));
        }
        return this.tryRequestLingxingApi(reqBody);
    }

    @Override
    protected List<TmpSyncLingxingToWmsOrderList> compareNewAndOldData(List<TmpSyncLingxingToWmsOrderList> newData, List<TmpSyncLingxingToWmsOrderList> oldData) {
//        return super.compareNewAndOldData(newData, oldData);
        return newData;
    }

    @Override
    protected boolean cmpNewAndOldEqualCond(TmpSyncLingxingToWmsOrderList newOne, TmpSyncLingxingToWmsOrderList oldOne) {
        if (newOne == null || oldOne == null)
            return false;

        return newOne.getWoId() == oldOne.getWoId()
                && Objects.equals(newOne.getSku(), oldOne.getSku());
    }

    @Override
    protected TmpSyncLingxingToWmsOrderList cmpNewAndOldInsertProc(TmpSyncLingxingToWmsOrderList newOne) {
        newOne.setFlag(2);
        return newOne;
    }

    @Override
    protected TmpSyncLingxingToWmsOrderList cmpNewAndOldUpdateProc(TmpSyncLingxingToWmsOrderList newOne, TmpSyncLingxingToWmsOrderList oldOne) {
        newOne.setFlag(1);
        return newOne;
    }

    @Override
    protected boolean cmpNewAndOldUpdateCond(TmpSyncLingxingToWmsOrderList newOne, TmpSyncLingxingToWmsOrderList oldOne) {
        return true;
    }

    @Override
    protected void saveTempToFormal() {
        service.clearAll(this.data_version);
        service.updateFlag(this.data_version);
        service.updateTo(this.data_version);
        service.insertInto(this.data_version);
    }

    @Override
    protected List<TmpSyncLingxingToWmsOrderList> jsonDumpsResult(JSONArray jsonArray) {
        List<TmpSyncLingxingToWmsOrderList> results = new ArrayList<>();
        for (Object obj: jsonArray) {
            JSONObject item = (JSONObject) obj;
            TmpSyncLingxingToWmsOrderList tmp = new TmpSyncLingxingToWmsOrderList();
            tmp.setVersion(this.data_version);
            tmp.setFlag(2); // Insert Flag
            tmp.setWoId(item.getInteger("wo_id"));
            tmp.setWoNumber(item.getString("wo_number"));
            tmp.setSid(item.getLong("sid"));
            tmp.setSellerName(item.getString("seller_name"));
            tmp.setSiteText(item.getString("site_text"));
            tmp.setWid(item.getInteger("wid"));
            tmp.setWarehouseName(item.getString("warehouse_name"));
            tmp.setWarehouseType(item.getInteger("warehouse_type"));
            tmp.setBatchNo(item.getString("batch_no"));
            tmp.setReferenceNo(item.getString("reference_no"));
            tmp.setWaybillNo(item.getString("waybill_no"));
            tmp.setTrackingNo(item.getString("tracking_no"));
            tmp.setPicker(item.getString("picker"));
            tmp.setPlatformName(item.getString("platform_name"));
            tmp.setPlatformOrderNo(item.getString("platform_order_no"));
            tmp.setOrderNumber(item.getString("order_number"));
            tmp.setOrderForm(item.getString("order_form"));
            tmp.setOrderType(item.getInteger("order_type"));
            tmp.setOrderOriginAmount(item.getString("order_origin_amount"));
            tmp.setOrderCurrencyCode(item.getString("order_currency_code"));
            tmp.setOrderCurrencyCode(item.getString("order_customer_service_notes"));
            tmp.setOrderBuyerNotes(item.getString("order_buyer_notes"));
            tmp.setStatus(item.getInteger("status"));
            tmp.setStatusName(item.getString("status_name"));
            tmp.setLogisticsStatus(item.getInteger("logistics_status"));
            tmp.setLogisticsStatusName(item.getString("logistics_status_name"));
            tmp.setLogisticsMessage(item.getString("logistics_message"));
            tmp.setLogisticsProviderId(item.getInteger("logistics_provider_id"));
            tmp.setLogisticsProviderName(item.getString("logistics_provider_name"));
            tmp.setLogisticsTypeId(item.getInteger("logistics_type_id"));
            tmp.setLogisticsTypeName(item.getString("logistics_type_name"));
            tmp.setLogisticsFreight(item.getString("logistics_freight"));
            tmp.setLogisticsFreightCurrencyCode(item.getString("logistics_freight_currency_code"));
            tmp.setIsCheck(item.getInteger("is_check"));
            tmp.setIsWeigh(item.getInteger("is_weigh"));
            tmp.setIsSurfacePrint(item.getInteger("is_surface_print"));
            tmp.setIsOrderPrint(item.getInteger("is_order_print"));
            tmp.setProcessSn(item.getString("process_sn"));
            tmp.setTargetCountry(item.getString("target_country"));
            tmp.setTagNames(item.getString("tag_names"));
            tmp.setPkgVolume(item.getString("pkg_volume"));
            tmp.setPkgLength(item.getString("pkg_length"));
            tmp.setPkgWeight(item.getString("pkg_weight"));
            tmp.setPkgRealWeight(item.getString("pkg_real_weight"));
            tmp.setPkgFeeWeight(item.getString("pkg_fee_weight"));
            tmp.setPkgWeightUnit(item.getString("pkg_weight_unit"));
            tmp.setPkgRealWeightUnit(item.getString("pkg_real_weight_unit"));
            tmp.setPkgFeeWeightUnit(item.getString("pkg_fee_weight_unit"));
            tmp.setPkgSizeUnit(item.getString("pkg_size_unit"));
            tmp.setRecipientTaxNo(item.getString("recipient_tax_no"));
            tmp.setSenderTaxNo(item.getString("sender_tax_no"));
            tmp.setDeliverer(item.getString("deliverer"));
            tmp.setDeliverDeadline(item.getString("deliver_deadline"));
            tmp.setDeliveredAt(item.getString("delivered_at"));
            tmp.setStockDeliveredAt(item.getString("stock_delivered_at"));
            tmp.setCreateAt(item.getString("create_at"));
            tmp.setPurchaseTime(item.getString("purchase_time"));
            tmp.setPaymentTime(item.getString("payment_time"));
            tmp.setSurfacePrintTime(item.getString("surface_print_time"));
            tmp.setOrderPrintTime(item.getString("order_print_time"));
            tmp.setPlatformPaymentTime(item.getString("platform_payment_time"));
            tmp.setPackageNo(item.getString("package_no"));
            tmp.setPackageDeliveredData(item.getString("package_delivered_data"));
            tmp.setTransferLogisticsCompanyCode(item.getString("transfer_logistics_company_code"));
            tmp.setTransferLogisticsCompanyId(item.getString("transfer_logistics_company_id"));
            tmp.setTransferTrackingNo(item.getString("transfer_tracking_no"));
            tmp.setIsLockStorage(item.getInteger("transfer_tracking_no"));
            tmp.setIsAdvanceDelivery(item.getInteger("is_advance_delivery"));
            tmp.setApportionStatus(item.getInteger("apportion_status"));
            tmp.setApportionMessage(item.getString("apportion_message"));
            tmp.setRemarkAttachment(item.getString("remark_attachment"));
            tmp.setConsignee(item.getString("consignee"));
            tmp.setConsigneePhone(item.getString("consignee_phone"));
            tmp.setConsigneePostcode(item.getString("consignee_postcode"));
            tmp.setConsigneeAddress(item.getString("consignee_address"));
            tmp.setConsigneeFullAddress(item.getString("consignee_full_address"));
            tmp.setSurfaceFileType(item.getString("surface_file_type"));
            JSONObject surface_file = item.getJSONObject("surface_file");
            if (surface_file != null) {
                tmp.setSurfaceFile(surface_file.toJSONString());
                tmp.setSurfaceFileUrl(surface_file.getString("uri"));
                tmp.setSurfaceFileExt(surface_file.getString("ext"));
                tmp.setSurfaceFileSize(surface_file.getString("size"));
            }
            JSONArray productInfoList = item.getJSONArray("product_info");

            if (productInfoList == null || productInfoList.isEmpty()) {
                results.add(tmp);
            }
            else {
                for (Object obj1 : productInfoList) {
                    JSONObject productInfo = (JSONObject) obj1;
                    TmpSyncLingxingToWmsOrderList tmp1 = new TmpSyncLingxingToWmsOrderList();
                    BeanUtils.copyProperties(tmp, tmp1);
                    tmp1.setFlag(1); // INSERT FLAG
                    tmp1.setWodId(productInfo.getInteger("wod_id"));
                    tmp1.setProductId(productInfo.getInteger("product_id"));
                    tmp1.setSku(productInfo.getString("sku"));
                    tmp1.setCount(productInfo.getInteger("count"));
                    tmp1.setBundleType(productInfo.getInteger("bundle_type"));
                    tmp1.setBundleWodId(productInfo.getInteger("bundle_wod_id"));
                    tmp1.setProductName(productInfo.getString("product_name"));
                    tmp1.setSellerSku(productInfo.getString("seller_sku"));
                    tmp1.setCustomization(productInfo.getString("customization"));
                    tmp1.setCnName(productInfo.getString("cn_name"));
                    tmp1.setEnName(productInfo.getString("en_name"));
                    tmp1.setThirdProductName(productInfo.getString("third_product_name"));
                    tmp1.setThirdProductCode(productInfo.getString("third_product_code"));
                    tmp1.setUnitPrice(productInfo.getString("unit_price"));
                    tmp1.setCurrencyCode(productInfo.getString("currency_code"));
                    tmp1.setApportionFreight(productInfo.getString("apportion_freight"));
                    tmp1.setApportionFreightSingle(productInfo.getString("apportion_freight_single"));
                    tmp1.setPLogisticsFreightCurrencyCode(productInfo.getString("logistics_freight_currency_code"));
                    tmp1.setStockCost(productInfo.getString("stock_cost"));
                    tmp1.setStockSid(productInfo.getString("stock_sid"));
                    tmp1.setStockSellerName(productInfo.getString("stock_seller_name"));
                    tmp1.setItemUnitPrice(productInfo.getString("item_unit_price"));
                    tmp1.setItemTotalPrice(productInfo.getString("item_total_price"));
                    tmp1.setRealWeightTotal(productInfo.getString("real_weight_total"));
                    tmp1.setFeeWeightTotal(productInfo.getString("fee_weight_total"));
                    tmp1.setVolumeWeightTotal(productInfo.getString("fee_weight_total"));
                    tmp1.setDeclaredCurrencyIcon(productInfo.getString("declared_currency_icon"));

                    results.add(tmp1);
                }
            }
        }

        return results;
    }

    @Override
    protected List<TmpSyncLingxingToWmsOrderList> getOldData(List<TmpSyncLingxingToWmsOrderList> newObjects) {
        return service.getList(newObjects);
    }

    @Override
    protected void saveData2TmpTb(List<TmpSyncLingxingToWmsOrderList> results) {
        service.saveBatch(results);
    }
}
